/**
 * @desc 我的
 */
<template>
    <view class="user">
        <nut-noticebar v-if="isNotice || !coach" text="尚未完善个人信息！" :background="`rgba(251, 248, 220, 1)`"
            :color="`#D9500B`"></nut-noticebar>
        <view class="user-top">
            <!-- 头像栏 -->
            <view v-if="isLogin" class="user-top-login">
                <nut-avatar size="large" :icon="avatarUrl">
                </nut-avatar>
                <view class="user-top-login-detail">
                    <view>{{ nickName }}</view>
                    <view v-if="!isCoach">{{ isAppointment ? `今天预约时间:${timeInfo[type]}` : '未预约' }}</view>
                    <view v-if="!isCoach">{{ coach ? `专属教练:${coach}` : '请去个人中心关联教练!' }}</view>
                </view>
            </view>
            <!-- 登录 -->
            <view v-else class="user-top-button">
                <nut-button plain type="primary" @click="getUserInfo">点击登录</nut-button>
            </view>
        </view>
        <!-- 其他入口 -->
        <view class="user-middle">
            <view class="user-middle-item" v-for="item in routes" :key="item.url" @click="goTo(item.url)">
                <view class="user-middle-item-left">
                    <nut-icon name="dongdong"></nut-icon>
                    <view>{{ item.name }}</view>
                </view>
                <nut-icon name="right"></nut-icon>
            </view>
        </view>
        <!-- 版本号 -->
        <view class="user-version">{{ version }}</view>
    </view>
</template>

<script>
import Taro from '@tarojs/taro';
import db from '../../server/index';
import { adminOpenid } from '../../utils/config'
const _ = db.command;
export default {
    name: 'User',
    components: {

    },
    data() {
        const { avatarUrl, nickName } = Taro.getStorageSync('userInfo');
        const {
            miniProgram
        } = Taro.getAccountInfoSync();
        const {
            version
        } = miniProgram
        return {
            isCoach: false, // 是否是教练
            coach: '', // 学员的教练是啥
            avatarUrl,
            visible: false,
            nickName,
            isSetting: true,
            timeInfo: {},
            version,
            isAppointment: false,
            isNotice: false,
            type: 1,
            isLogin: avatarUrl && nickName,
            routes: [
                {
                    url: '/pages/appointment/index',
                    name: '预约学车',
                    icon: ''
                },
                {
                    url: '/pages/log/index',
                    name: '学车生涯',
                    icon: ''
                },
                {
                    url: '/pages/today/index',
                    name: '今日学车',
                    icon: ''
                },
                {
                    url: '/pages/apply/index',
                    name: '成为教练',
                    icon: ''
                },
                {
                    url: '/pages/message/index',
                    name: '意见反馈',
                    icon: ''
                },
            ]
        }
    },
    created() {
        db.collection('setting').get().then(({ data = [] }) => {
            if (data.length) {
                if (data[0].open) {
                    this.routes.splice(3, 0, {
                        url: '/pages/phone/index',
                        name: '个人中心',
                        icon: ''
                    })
                }
            } else {
                db.collection('setting').add({
                    data: {
                        open: false
                    }
                })
            }
        })
        // 增加小程序分享
        Taro.showShareMenu({
            withShareTicket: true
        })
    },
    onShow() {
        this.init()
    },
    onPullDownRefresh() {
        Taro.showLoading({
            title: '加载中',
        })
        this.init()
    },
    methods: {
        // 查看是否是教练
        checkCoach() {
            db.collection('coach').where({
                openid: Taro.getStorageSync('openid'),
                stop: false // 是教练 
            }).get().then(({ data = [] }) => {
                if (data.length) {
                    this.isCoach = true
                    this.routes = [
                        {
                            url: '/pages/appointment/index',
                            name: '预约学车',
                            icon: ''
                        },
                        {
                            url: '/pages/today/index',
                            name: '今日学车',
                            icon: ''
                        },
                        {
                            url: '/pages/total/index',
                            name: '学员预览',
                            icon: ''
                        },
                        {
                            url: '/pages/work/index',
                            name: '选择休息日',
                            icon: ''
                        },
                        {
                            url: '/pages/apply/index',
                            name: '成为教练',
                            icon: ''
                        },
                        {
                            url: '/pages/time/index',
                            name: '设置',
                            icon: ''
                        },
                        {
                            url: '/pages/message/index',
                            name: '意见反馈',
                            icon: ''
                        },
                    ]
                } else {
                    this.isCoach = false
                }
            })
        },
        // 跳转页面
        goTo(url) {
            if (!this.avatarUrl || !this.nickName) {
                Taro.showToast({
                    title: '请先点击登录!',
                    icon: 'none',
                    duration: 2000,
                    mask: true
                })
                return
            }
            // 完善个人信息
            if (['/pages/appointment/index', '/pages/log/index', '/pages/today/index'].includes(url)) {
                db.collection('coach').where({
                    openid: Taro.getStorageSync('openid')
                }).get().then(({ data = [] }) => {
                    // 带审核教练 
                    if (data.length) {
                        if (data[0].stop) {
                            Taro.showToast({
                                title: '教练申请审核中,如果你是学员，去申请教练中撤销申请!',
                                icon: 'none',
                                duration: 2000,
                                mask: true
                            })
                        } else {
                            // 你是教练
                            Taro.navigateTo({
                                url
                            })
                        }
                    } else {
                        db.collection('phone').where({
                            _openid: Taro.getStorageSync('openid')
                        }).get().then(({ data = [] }) => {
                            if (data.length) {
                                const { coachId } = data[0]
                                if (!coachId) {
                                    Taro.showToast({
                                        title: '请完善个人信息中教练选择!',
                                        icon: 'none',
                                        duration: 2000,
                                        mask: true
                                    })

                                    return
                                }
                                Taro.navigateTo({
                                    url
                                })
                            } else {
                                Taro.showToast({
                                    title: '请完善个人信息!',
                                    icon: 'none',
                                    duration: 2000,
                                    mask: true
                                })
                            }
                        })
                    }
                })
            } else {
                Taro.navigateTo({
                    url
                })
            }
        },
        init() {
            wx.cloud.callFunction({
                name: 'getopenid',
                complete: res => {
                    const { result } = res;
                    const { openid } = result || {};
                    // 今天时间
                    let a = new Date();
                    let year = a.getFullYear();
                    let month = (a.getMonth() + 1 + '').padStart(2, 0);
                    let day = (a.getDate() + '').padStart(2, 0)
                    const start = new Date(`${year}-${month}-${day} 00:00:00`.replace(/-/g, '/')).getTime();
                    const end = new Date(`${year}-${month}-${day} 23:59:59`.replace(/-/g, '/')).getTime();
                    Taro.setStorageSync('openid', openid);
                    this.checkCoach();
                    // 是否添加route,管理员权限 
                    if (adminOpenid.includes(openid) && this.isSetting) {
                        this.routes.push({
                            url: '/pages/time/index',
                            name: '设置',
                            icon: ''
                        }, {
                            url: '/pages/coach/index',
                            name: '教练组',
                            icon: ''
                        })
                        this.isSetting = false
                    }
                    // 获取手机号
                    db.collection('phone').where({
                        _openid: openid
                    }).get().then(({ data = [] }) => {
                        this.isNotice = !data.length
                        if (!data[0].coachId) {
                            return
                        }
                        // 优化
                        data.length && db.collection('time').where({
                            coachId: data[0].coachId
                        }).get().then(({ data = [] }) => {
                            data.forEach(item => {
                                this.timeInfo[item._id] = `${item.startTime}---${item.endTime}`
                            })
                        })
                        // 教练名称
                        data.length && db.collection('coach').where({
                            _id: data[0].coachId
                        }).get().then(({ data = [] }) => {
                            this.coach = data.length ? data[0].coach : '';
                        })

                        // 检查当前用是否预约了
                        data.length && db.collection('user').where({
                            _openid: openid,
                            done: true,
                            coachId: data[0].coachId,
                            createTime: _.gte(start).and(_.lte(end))
                        }).get().then(({ data = [] }) => {
                            if (data.length) {
                                this.isAppointment = true;
                                this.type = data[0].type;
                            } else {
                                this.isAppointment = false;
                                this.type = ''
                            }
                        })
                        Taro.stopPullDownRefresh();
                        Taro.hideLoading();
                    })
                }
            })
        },
        getUserInfo() {
            Taro.getUserProfile({
                desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
                success: (res) => {
                    // 开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
                    const { userInfo } = res
                    const { avatarUrl, nickName } = userInfo
                    this.avatarUrl = avatarUrl
                    this.nickName = nickName
                    Taro.setStorageSync('userInfo', userInfo)
                    this.isLogin = true
                }
            })
        },
    }
}
</script>

<style lang="less">
.user {
    &-top {
        width: 100%;
        height: 150px;
        background-color: rgb(146, 182, 250);

        &-button {
            padding-top: 20px;
            text-align: center;
        }

        &-bottom {
            display: flex;
            justify-content: center;
            margin-top: 20px;

            &-item {
                text-align: center;
                margin: 0 20px;

                >view {
                    color: #fff;

                    &:last-of-type {
                        font-size: 14px;
                    }
                }
            }
        }

        &-login {
            margin-left: 10px;
            padding-top: 20px;
            display: flex;

            &-detail {
                margin-left: 10px;
                display: flex;
                flex-direction: column;

                >view {
                    color: #fff;
                    font-size: 16px;

                    &:not(:first-of-type) {
                        font-size: 14px;
                        margin-top: 8px;
                    }
                }
            }
        }
    }

    &-middle {
        margin-top: 20px;

        &-item {
            padding: 0 5px;
            display: flex;
            justify-content: space-between;
            height: 50px;
            align-items: center;
            border-bottom: 1px solid rgb(243, 242, 242, .6);

            &-left {
                display: flex;
                align-items: center;
            }
        }
    }

    &-version {
        text-align: center;
        font-size: 14px;
        margin-top: 50px;
    }
}
</style>
